package cn.icyzx.configure;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.io.IOException;
import java.util.Properties;

/**
 * Created by zk on 2016/11/12.
 * 这个应用上下文代表了整个spring的上下文，能被多个dispatcherServlet上下文公用
 * 常用来放置Controller，cn.icyzx.service,Repository 和其它服务类型的bean
 */

@Configuration
@ComponentScan(basePackages = "cn.icyzx.controller,cn.icyzx.service,cn.icyzx.dao,cn.icyzx.models,cn.icyzx.filter")
public class RootConfig {

    private static Logger logger = Logger.getLogger(RootConfig.class);


    /**
     * javaMailSender spring所提供的emailBean
     *
     * @param
     * @return org.springframework.mail.javamail.JavaMailSenderImpl
     */
    @Bean("javaMailSender")
    public JavaMailSenderImpl javaMailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        final String host;
        final String username;
        final String password;
        final String port;

        Properties properties = new Properties();
        try {
            properties.load(RootConfig.class.getClassLoader().getResourceAsStream("email.properties"));
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("can't find email.properties");
        }

        try {
            host = properties.getProperty("host");
            if (host != null)
                javaMailSender.setHost(host);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("can't  initialize email host");
        }

        try {
            username = properties.getProperty("username");
            if (username != null)
                javaMailSender.setUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("can't  initialize email username");
        }

        try {
            password = properties.getProperty("password");
            if (null != password)
                javaMailSender.setPassword(password);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("can't  initialize email password");
        }

        try {
            port = properties.getProperty("port");
            if (null != port && !"".equals(port))
                javaMailSender.setPort(Integer.parseInt(port));
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("can't  initialize email port");
        }

        logger.info("initialize javaMailSender");

        return javaMailSender;
    }


}
